package com.eqxiu.js;


import com.alibaba.fastjson.JSONObject;

import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class JavaScriptProvider {


    public static Invocable invocable;

    public static void  initJavaScript(String pathes) throws Exception {
        // 创建一个脚本引擎管理器
        ScriptEngineManager manager = new ScriptEngineManager();
        // 获取一个指定的名称的脚本引擎
        ScriptEngine engine = manager.getEngineByName("js");
        // 获取js文件所在目录的路径

        String[] array = pathes.split(",");

        engine.eval(new FileReader(array[0]));
        engine.eval(new FileReader(array[1]));
        // 从脚本引擎中返回一个给定接口的实现

        invocable = (Invocable) engine;
    }


    public static JSONObject getDeviceInfo(String ua) throws Exception{
        Object obj = invocable.invokeFunction("tracker_ua_device",ua);

        JSONObject json =(JSONObject)JSONObject.toJSON(obj);
        return json;
    }

    public static void main(String[] args) {
        try {
            JavaScriptProvider jsProvider = new JavaScriptProvider();
            jsProvider.initJavaScript( "/Users/wangjunbo/IdeaProjects/tracker-js/js/tracker_ua_base.js,/Users/wangjunbo/IdeaProjects/tracker-js/js/tracker_ua_device.js");
            JSONObject j = getDeviceInfo("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
            String model = j.getJSONObject("device").getString("model");
            String os = j.getJSONObject("os").getString("name");
            System.out.println(model);
            System.out.println(os);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
